<template>
  <div v-show="showDialog && !detailInfo.visible">
    <div class="width100">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="closeDetailList">订单页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
        </new-page-filter>
        <div class="display-flex">
          <Group-select
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
          ></Group-select>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        v-if="groupFlag"
        class="groupFlag-container"
        :is-group-search="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="false"
        :pager="false"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          {{ scope.row.orderNo }}
        </template>
      </table-container>
      <table-container
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="true"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-deliverQty="scope">
                  <span v-if="scope.row.deliverQty">
                    {{ scope.row.deliverQty + scope.row.preNetworkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-receivingQty="scope">
                  <span v-if="scope.row.receivingQty">
                    {{ scope.row.receivingQty + scope.row.preNetworkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-preNetworkPrice="scope">
                  <span v-if="scope.row.preNetworkPrice">
                    {{ scope.row.preNetworkPrice + '元/' + scope.row.preNetworkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-returnQty="scope">
                  <span v-if="scope.row.returnQty">
                    {{ scope.row.returnQty+ scope.row.preNetworkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
      </table-container>
    </div>
  </div>
  <rejectedOrderDetail
    v-if="detailInfo.visible"
    v-model:visible="detailInfo.visible"
    :orderId="detailInfo.orderId"
    @returnBack="getList"
  />
  <set-preference
    v-if="preferenceInfo.visible"
    v-model:visible="preferenceInfo.visible"
    :search-list="filterInfo.searchList"
    :field-list="tableInfo.fieldList"
    :customize-user-v-o="filterInfo.query.customizeUserVO"
    @callback="setPreferenceCallback"
  />
  <advanced-search
    v-if="advancedSearchInfo.visible"
    v-model:visible="advancedSearchInfo.visible"
    :field-list="tableInfo.fieldList"
    v-model:form-data="advancedSearchInfo.data"
    @callback="advancedSearchCallback"
  />
</template>
<script setup name="rejectedDetailList">
import { provinceReturnOrderDetail,groupsProvinceReturnOrderDetail,modifyProvinceReturnOrder } from "@/api/province";
import { getCustomizeSetting, updateUserCustomize } from "@/api/customize";
import rejectedOrderDetail from "./detail";
const emits = defineEmits();
const { proxy } = getCurrentInstance();
const props = defineProps(["visible"]);

const groupFlag = ref(false);
// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
});
const preferenceInfo = ref({
  visible: false,
});
const advancedSearchInfo = ref({
  visible: false,
  data: {},
});
const clearType = ref(true);
const slipSelectRequest = ref(true);
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: "",
    copyQueryMap: {},
    groupMap: {},
    groups: [],
    queryMap: {
      deptAuth: {
        asTbName: "purch_order",
        columnName: "dept_id",
        queryType: "IN",
        queryCategory: "AND",
        value: "deptAuth",
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: "button", label: "搜索", event: search },
    { type: "button", label: "高级查询", event: advancedSearchShow },
    { type: "button", label: "重置", event: clearSearch },
  ],
});
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
});
//明细相关
const detailInfo = ref({
  visible: false,
  orderId: "",
});
const tableKey = ref(
  "provinceReturnOrderDetailList-com.slip.spd.entity.vo.provincePlatform.ProvinceReturnOrderDetailVO"
);
const showDialog = computed({
  get() {
    return props.visible;
  },
  set(newValue) {
    emits("update:visible", newValue); // 更新父组件visible
  },
});

setData();
function setData() {
  let obj = {
    receivingQty: {
      label: "收货数量",
      value: "receivingQty",
      type: "slot",
      minWidth: "250px",
      hidden: true,
    },
    returnQty: {
      label: "退货数量",
      value: "returnQty",
      type: "slot",
      minWidth: "250px",
      hidden: true,
    },
    deliverQty: {
      label: "配送数量",
      value: "deliverQty",
      type: "slot",
      minWidth: "250px",
      hidden: true,
    },
    preNetworkPrice: {
      label: "省采单价",
      value: "preNetworkPrice",
      type: "slot",
      minWidth: "250px",
      hidden: true,
    },
    statusValue: {
      label: "状态",
      value: "statusValue",
      asValue: "status",
      componentType: "select-model",
      code: "province_platform_order_status",
      show: false,
      hidden: true,
    },
    networkProductTypeValue: {
      label: "挂网产品类型",
      value: "networkProductTypeValue",
      asValue: "networkProductType",
      componentType: "select-model",
      code: "network_product_type",
      show: false,
      hidden: true,
    },
  };
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  });
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    commonName: {
      label: "通用名称",
      value: "commonName",
      componentType: "input",
      show: false,
      hidden: true,
    },
  });
  getCustomize();
}
function closeDetailList() {
  proxy.$store.dispatch("app/toggleOpenFilter");
  showDialog.value = false;
  emits("callback");
}
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr;
  groupSelectInfo.value.selections = arr;
  if (!arr.length) {
    filterInfo.value.query.groups = [];
    filterInfo.value.query.groupMap = {};
    groupSelectInfo.value.data = [];
    groupFlag.value = false;
  }
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value);
    }
  });
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true;
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random();
}
function clearSearch() {
  clearType.value = !clearType.value;
  advancedSearchInfo.value.data = {};
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  );
  search();
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case "tableCheck":
      tableInfo.value.selections = [...data];
      break;
  }
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr);
    filterInfo.value.sortArr = arr;
    filterInfo.value.query.sortString = arr.length ? arr.toString() : "";
    getList();
  }
}
//展示明细
function showDetail(row) {
  detailInfo.value.orderId = row.orderId;
  detailInfo.value.visible = true;
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true;
    filterInfo.value.query.groups = arr;
    groupSelectInfo.value.selections = arr;
    getCustomizeGroupsList();
  } else {
    proxy.$message.warning({
      message: "请选择分组条件！",
      showClose: true,
      duration: 3000,
    });
  }
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {};
  if (len) {
    params = param;
  } else {
    params = filterInfo.value.query;
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params);
    params.queryMap = {};
  }
  await groupsProvinceReturnOrderDetail(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data;
      let newData = [];
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          });
        });
        expande.children = newData;
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          });
        });
        groupSelectInfo.value.data = newData;
      }
    }
  });
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length;
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      };
      getCustomizeGroupsList(len, params, data);
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      };
      modifyProvinceReturnOrder(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data;
          await resData.forEach((item, index) => {
            item.id = index + Math.random();
            item.isColspan = false;
          });
          data.children = resData;
        }
      });
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }];
  }
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value;
  _filterInfo.query.queryMap = {};
  let arr = [
    {
      fieldName: "deptId",
      queryType: "IN",
      queryCategory: "AND",
      value: "deptAuth",
    },
  ];
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr];
  advancedSearchInfo.value.data = obj.data;
  if (groupSelectInfo.value.selections.length > 0) {
    await getCustomizeGroupsList();
  } else {
    groupSelectInfo.value.data = [];
    await getList();
  }
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  );
  clearType.value = !clearType.value;
}
// 搜索
function search() {
  advancedSearchInfo.value.data = {};
  filterInfo.value.query.queryDtoList = [];
  if (groupSelectInfo.value.selections.length > 0) {
    getCustomizeGroupsList();
  } else {
    groupSelectInfo.value.data = [];
    tableInfo.value.initCurpage = Math.random();
    tableInfo.value.refresh = Math.random();
  }
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value;
  let _filterInfo = filterInfo.value;
  let param = {
    tableKey: tableKey.value,
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      filterInfo.value.query.customizeUserVO = data;
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      );
      let tableFieldInfo = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail,
        true
      );
      _tableInfo.fieldList = tableFieldInfo.fieldList;
      groupSelectInfo.value.options = tableFieldInfo.groupOption;
      console.log(tableFieldInfo)
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      };
      _filterInfo.searchList = searchInfo.searchList;
      _filterInfo.searchList.forEach((item) => {
        item.event = search;
      });
      _filterInfo.copyQueryMap = proxy.$fn.deepClone(
        _filterInfo.query.queryMap
      );
      slipSelectRequest.value = _slipSelectRequest;
      _tableInfo.api = provinceReturnOrderDetail;
      getList();
    }
  });
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return "bg-color-EBEEF5";
  } else {
    return "";
  }
}
function arraySpanMethod({ row, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return [1, tableInfo.value.fieldList.length + 1];
    }
  }
}
</script>

<style scoped></style>
